import 'package:mobx/mobx.dart';
import '../models/scan_result_model.dart';
import '../services/scan_result_service.dart';
import 'auth_store.dart';

part 'scan_result_store.g.dart';

class ScanResultStore = _ScanResultStore with _$ScanResultStore;

abstract class _ScanResultStore with Store {
  final ScanResultService _scanResultService = ScanResultService();
  final AuthStore _authStore;

  _ScanResultStore(this._authStore);

  @observable
  ObservableList<ScanResultModel> scanResults =
      ObservableList<ScanResultModel>();

  @observable
  ScanResultModel? currentScanResult;

  @observable
  bool isLoading = false;

  @observable
  String? errorMessage;

  @computed
  List<ScanResultModel> get userScanResults {
    if (_authStore.currentUser == null) return [];
    return scanResults
        .where((scan) => scan.userId == _authStore.currentUser!.id)
        .toList();
  }

  @computed
  List<ScanResultModel> get favoriteScanResults {
    return scanResults.where((scan) => scan.isFavorite).toList();
  }

  @action
  Future<void> loadScanResults() async {
    isLoading = true;
    errorMessage = null;

    try {
      // 始终获取所有扫描结果，无论用户是否登录
      final allResults = _scanResultService.getAllScanResults();
      scanResults.clear();
      scanResults.addAll(allResults);
      isLoading = false;
    } catch (e) {
      errorMessage = 'Load scan results failed: ${e.toString()}';
      isLoading = false;
    }
  }

  @action
  Future<ScanResultModel?> createScanResult({
    required String imageUrl,
    required String result,
    required String description,
  }) async {
    if (_authStore.currentUser == null) return null;

    isLoading = true;
    errorMessage = null;

    try {
      final scanResult = await _scanResultService.createScanResult(
        userId: _authStore.currentUser!.id,
        imageUrl: imageUrl,
        result: result,
        description: description,
      );

      scanResults.insert(0, scanResult); // 添加到列表开头
      isLoading = false;
      return scanResult;
    } catch (e) {
      errorMessage = 'Create scan result failed: ${e.toString()}';
      isLoading = false;
      return null;
    }
  }

  @action
  Future<void> toggleFavorite(String scanResultId) async {
    try {
      await _scanResultService.toggleFavorite(scanResultId);

      // 更新本地状态
      final index = scanResults.indexWhere((scan) => scan.id == scanResultId);
      if (index >= 0) {
        final updatedScan = _scanResultService.getScanResultById(scanResultId);
        if (updatedScan != null) {
          scanResults[index] = updatedScan;
        }
      }

      // 更新当前选中的扫描结果
      if (currentScanResult?.id == scanResultId) {
        currentScanResult = _scanResultService.getScanResultById(scanResultId);
      }
    } catch (e) {
      errorMessage = 'Update favorite status failed: ${e.toString()}';
    }
  }

  @action
  Future<void> deleteScanResult(String scanResultId) async {
    isLoading = true;
    errorMessage = null;

    try {
      await _scanResultService.deleteScanResult(scanResultId);
      scanResults.removeWhere((scan) => scan.id == scanResultId);
      if (currentScanResult?.id == scanResultId) {
        currentScanResult = null;
      }
      isLoading = false;
    } catch (e) {
      errorMessage = 'Delete scan result failed: ${e.toString()}';
      isLoading = false;
    }
  }

  @action
  void selectScanResult(String scanResultId) {
    currentScanResult = _scanResultService.getScanResultById(scanResultId);
  }

  @action
  Future<List<ScanResultModel>> searchScanResults(String query) async {
    isLoading = true;
    errorMessage = null;

    try {
      final results = _scanResultService.searchScanResults(query);
      isLoading = false;
      return results;
    } catch (e) {
      errorMessage = 'Search scan results failed: ${e.toString()}';
      isLoading = false;
      return [];
    }
  }
}
